package com.example.utils;

import com.example.result.R;
import io.jsonwebtoken.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

/**
 * @Date 2022/10/3
 * @Description
 */
@Slf4j
@Data
@Component
@ConfigurationProperties("jwt.data")
public class JWTUtils {

    //密钥
    public String SECRET;
    //Authorization
    private String header;
    //过期时间
    private int expiration;

    //创建token
    //传入userId
    public String createToken(Long userId) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, expiration);
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId + "")
                .setIssuedAt(new Date())
                .setExpiration(calendar.getTime())
                .signWith(SignatureAlgorithm.HS256, SECRET);
        return builder.compact();
    }

    //解析jwt
    public Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("jwt match error:{}", e);
            return null;
        }
    }

    //验证jwt
    public R validateToken(String token) {
        Claims claims = null;
        try {
            claims = parseToken(token);
            return R.success(null, "验证成功");
        } catch (ExpiredJwtException e) {
            return R.fail("token已过期");
        } catch (Exception e) {
            return R.fail("未登录");
        }

    }

    //判断token是否过期
    public boolean judgeTokenExpiration(Date expiration) {
        return expiration.before(new Date());
    }
}
